//
//  PersonSelectViewController.m
//  MobileOffice
//
//  Created by jjkj on 16/12/7.
//  Copyright © 2016年 liaoningjujin. All rights reserved.
//

#import "PersonSelectViewController.h"
#import "PersonSelectTableViewCell.h"
#import "StatisticsListViewController.h"

@interface PersonSelectViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;//职责列表
    //NSMutableArray *_dataArr;//选择的数据数组
    NSMutableDictionary *_dataDict;//数组字典
    NSMutableArray *_dictKeys;
    //UIView *_headView;//头视图
}
@property (nonatomic,strong) NSMutableArray *sonArr;//子部门数组
@property (nonatomic,strong) UIButton *backButton;//返回上一级
@property (nonatomic,strong) NSMutableArray *personArr;//选择要查询人员的数组
@end

@implementation PersonSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setLeftBackNavigation];
    [self setNavigationTitle:@"筛选"];
    [self creatView];
    // Do any additional setup after loading the view.
}


#pragma mark - creatTableView
- (void)creatView{
    //_dataArr=[NSMutableArray new];
    _sonArr=[NSMutableArray new];
    _dataDict=[NSMutableDictionary new];
    
        //遍历所有部门和人员  将选中的状态切换为未选中
    for (ManageStrutureModel *model in self.manageModel.dataArr) {
        model.isSelect=NO;
    }
    for (NSInteger i=0; i<self.manageModel.dataDict.allKeys.count; i++) {
        NSMutableArray *modelArr=self.manageModel.dataDict[self.manageModel.dataDict.allKeys[i]];
        for (ManageStrutureModel *model in modelArr) {
            model.isSelect=NO;
        }
    }
    //初始化数据源 将一级部门放进数据源
    if (self.manageModel.dataArr.count>0) {
        ManageStrutureModel *model=[self.manageModel.dataArr firstObject];
        NSMutableArray *newArr=[NSMutableArray new];
        [newArr addObject:self.manageModel];
        [_dataDict setObject:newArr forKey:model.levelType];
        [self refreshDictKeys];
    }

    _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT-64-80) style:UITableViewStylePlain];
    //_myTableView.backgroundColor=[UIColor redColor];
    _tableView.delegate=self;
    _tableView.dataSource=self;
    _tableView.tag=110;
    _tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator=NO;
    _tableView.showsHorizontalScrollIndicator=NO;
    _tableView.bounces=NO;
    //[self addTableViewUpdateRefresh:_tableView BindingIdentity:@""];
    //    [self addTableViewLoadMoreData:_tableView BindingIdentity:@""];
    [self.view addSubview:_tableView];
    
    
    
    //添加提交和存草稿button
    UIView *footView=[[UIView alloc]initWithFrame:CGRectMake(0, IPHONE_HEIGHT-80-64, IPHONE_WIDTH, 80)];
    footView.backgroundColor=[UIColor clearColor];
    
    NSArray *title=@[@"提交"];
    CGFloat buttonWidth=(IPHONE_WIDTH-(title.count+1)*10)/title.count;
    for (int i=0; i<title.count; i++) {
        UIButton *submitButton=[MyControl creatButtonWithFrame:CGRectMake(10*(i+1)+buttonWidth*i,20, buttonWidth, 40) target:self sel:@selector(submitClick:) tag:120+i image:nil title:title[i]];
        submitButton.layer.masksToBounds=YES;
        submitButton.layer.cornerRadius=5;
        [submitButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        if (i==0) {
            submitButton.backgroundColor=COLOR_MIDBLUE;
        }else{
            submitButton.backgroundColor=[UIColor orangeColor];
        }
        [footView addSubview:submitButton];
    }
    [self.view addSubview:footView];
}

#pragma mark -提交按钮
- (void)submitClick:(UIButton *)button{
    NSString *personStr=@"";
    NSString *departStr=@"";
    NSString *depOrEmp=@"";
    //人员和部门数组
    NSMutableArray *personArr=[NSMutableArray new];
    NSMutableArray *departArr=[NSMutableArray new];
//    for (ManageStrutureModel *model in self.manageModel.dataArr) {
//        if (model.isSelect) {
//            [departArr addObject:model.itemId];
//        }
//    }
    //遍历所有部门和人员  将选中的提取出来
    for (NSInteger i=0; i<self.manageModel.dataDict.allKeys.count; i++) {
        NSMutableArray *modelArr=self.manageModel.dataDict[self.manageModel.dataDict.allKeys[i]];
        for (ManageStrutureModel *model in modelArr) {
            if (model.isSelect) {
                if ([model.isDepart isEqualToString:@"0"]) {
                    [personArr addObject:model.itemId];
                }else{
                    [departArr addObject:model.itemId];
                }
            }
        }
    }
    personStr=[personArr componentsJoinedByString:@","];
    departStr=[departArr componentsJoinedByString:@","];
//    //去掉前面的逗号
//    if (personStr.length>0) {
//        if ([[personStr substringToIndex:1]isEqualToString:@","]) {
//            personStr=[personStr substringFromIndex:1];
//        }
//    }
//    if (departStr.length>0) {
//        if ([[departStr substringToIndex:1]isEqualToString:@","]) {
//            departStr=[departStr substringFromIndex:1];
//        }
//    }
    //0：个人，1：部门
    if (personStr.length==0&&departStr.length==0) {
        [self backClick];
        return;
    }
    if (personStr.length>0) {
        depOrEmp=@"0";
        if (self.myBlock) {
            self.myBlock(depOrEmp,personStr,nil);
            [self backClick];
        }
    }else{
        depOrEmp=@"1";
        if (self.myBlock) {
            if (self.isPersonInfo) {
                StatisticsListViewController *listView=[StatisticsListViewController new];
                listView.memberNames=departStr;
                [self.navigationController pushViewController:listView animated:YES];
            }else{
                self.myBlock(depOrEmp,nil,departStr);
                [self backClick];
            }

        }
    }

}



#pragma mark -返回上一级按钮点击
- (void)backButtonClick{
    //删除最后一项
    [_dataDict removeObjectForKey:_dictKeys.lastObject];
    [self refreshDictKeys];
    [_tableView reloadData];
}

#pragma mark -按照级别排序呢
- (void)refreshDictKeys{
    //因为key是无序的  所以用冒泡排序整理
    _dictKeys=[NSMutableArray arrayWithArray:_dataDict.allKeys];
    if (_dictKeys.count<2) {
        return;
    }
    NSString *temp;
    //冒泡排序
    for ( int j = 0; j < _dictKeys.count - 1; j++){
        for ( int i = 0; i < _dictKeys.count - 1 - j; i++)
        {
            //字符串比较  前面大
            if([_dictKeys[i] compare: _dictKeys[i + 1]]==NSOrderedDescending)
            {
                temp = _dictKeys[i];
                _dictKeys[i] = _dictKeys[i + 1];
                _dictKeys[i + 1] = temp;
            }
        }
    }
}

#pragma mark -增加部门或人员到列表中
- (void)addManageModelWithModel:(ManageStrutureModel *)parentModel{
//    //查找子部门或人员
//    NSMutableArray *modelArr=[self.manageModel.dataDict objectForKey:parentModel.itemId];
    //查找父部门数组
    NSMutableArray *parentsArr=[self.manageModel.dataDict objectForKey:parentModel.parentItemId];
    NSString *grandFatherStr=@"";
    if (parentsArr.count>0) {
        ManageStrutureModel *model=[parentsArr firstObject];
        grandFatherStr=model.parentItemId;
    }
    
//    parentModel.dataArr=modelArr;
//    if (modelArr!=nil&&modelArr.count>0) {
        //取出第一个model 用他的levelType在字典中查找
//        ManageStrutureModel *model=[modelArr firstObject];
//        NSMutableArray *levelTypeArr=_dataDict[model.levelType];
    if (parentsArr!=nil) {
        //遍历父部门 如果有其他选中也放入数组中
        for (ManageStrutureModel *parentsModel in parentsArr) {
            if (parentsModel.isSelect) {
                //如果父部门选中  则找出子部门
                NSMutableArray *sonArr=[self.manageModel.dataDict objectForKey:parentsModel.itemId];
                parentsModel.dataArr=sonArr;
                ManageStrutureModel *model=nil;
                //取出子部门的级别 在数据源字典中查找
                if (sonArr.count>0) {
                    model=[sonArr firstObject];
                }
                NSMutableArray *levelTypeArr=_dataDict[model.levelType];
                //如果找的到直接添加
                if (levelTypeArr) {
                    if (![levelTypeArr containsObject:parentsModel]) {
                        [levelTypeArr addObject:parentsModel];
                        //刷新key数组
                        [self refreshDictKeys];
                        [_tableView reloadData];
                    }
                }else{
                //如果没有则创建
                    if (model==nil||model.levelType==nil) {
                        return;
                    }
                    levelTypeArr=[NSMutableArray new];
                    [levelTypeArr addObject:parentsModel];
                    [_dataDict setObject:levelTypeArr forKey:model.levelType];
                    [self refreshDictKeys];
                    [_tableView reloadData];
                }
            }
        }
    }else{//如果父部门数组为空 则直接添加
        //查找子部门或人员
        NSMutableArray *modelArr=[self.manageModel.dataDict objectForKey:parentModel.itemId];
        parentModel.dataArr=modelArr;
        if (modelArr!=nil&&modelArr.count>0) {
            //取出第一个model 用他的levelType在字典中查找
            ManageStrutureModel *model=[modelArr firstObject];
            NSMutableArray *levelTypeArr=_dataDict[model.levelType];
            if (levelTypeArr) {
                if (![levelTypeArr containsObject:parentModel]) {
                    [levelTypeArr addObject:parentModel];
                    //刷新key数组
                    [self refreshDictKeys];
                    [_tableView reloadData];
                }
            }else{
                if (model==nil||model.levelType==nil) {
                    return;
                }
                //如果没有则创建
                levelTypeArr=[NSMutableArray new];
                [levelTypeArr addObject:parentModel];
                [_dataDict setObject:levelTypeArr forKey:model.levelType];
                [self refreshDictKeys];
                [_tableView reloadData];
            }
        }
    }

 //   }
}

#pragma mark -从列表中删除部门或人员
- (void)deleteManageModelWithModel:(ManageStrutureModel *)parentModel{
    //查找子部门或人员
    NSMutableArray *modelArr=[self.manageModel.dataDict objectForKey:parentModel.itemId];
    parentModel.dataArr=modelArr;
    if (modelArr!=nil&&modelArr.count>0) {
        //取出第一个model 用他的levelType在字典中查找
        ManageStrutureModel *model=[modelArr firstObject];
        NSMutableArray *levelTypeArr=_dataDict[model.levelType];
        if (levelTypeArr) {
            if ([levelTypeArr containsObject:parentModel]) {
                [levelTypeArr removeObject:parentModel];
                [self refreshDictKeys];
                [_tableView reloadData];
            }
        }
//        NSMutableArray *deleteArr=[NSMutableArray new];
//        //循环遍历子项
////        for (int j=0; j<parentModel.dataArr.count; j++) {
////            ManageStrutureModel *parent=parentModel.dataArr[j];
//            for (int i=0; i<_dataArr.count; i++) {
//                ManageStrutureModel *model=_dataArr[i];
//                //遍历要删除的部门下所有的子部门和个人 直到不是个人才停止
//                if ([model.itemId isEqualToString:parentModel.itemId]&&[model.isDepart isEqualToString:@"1"]) {
//                    for (int j=0; j<model.dataArr.count; j++) {
//                        ManageStrutureModel *newModel=parentModel.dataArr[j];
//                        if ([model.itemId isEqualToString:newModel.itemId]) {
//                            [self deleteManageModelWithModel:newModel];
//                            [deleteArr addObject:model];
//                        }
//                    }
//                }else{
////                    if ([_dataArr containsObject:model]) {
////                        [_dataArr removeObject:model];
////                    }
//                }
//            }
//        }
    }
//    [self refreshDictKeys];
//    [_tableView reloadData];
}

#pragma mark - TableViewDelagate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_dataDict.allKeys.count>=2) {
        return 2;
    }else{
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //如果超过2个 只显示2个分级
    if (_dataDict.allKeys.count>=2) {
        NSMutableArray *levelTypeArr=[_dataDict objectForKey:_dictKeys[_dictKeys.count-2+section]];
        return levelTypeArr.count;
    }else if (_dataDict.allKeys.count>0){
        NSMutableArray *levelTypeArr=[_dataDict objectForKey:[_dictKeys firstObject]];
        return levelTypeArr.count;
    }
    return 0;
}

//- (NSString *)getParentsIdWithModel:(ManageStrutureModel *)sonModel{
//    //遍历数组获取他的父model
//    NSString *parentId=nil;
//    for (NSInteger i=0; i<_dataDict.allKeys.count; i++) {
//        NSMutableArray *arr=_dataDict[_dataDict.allKeys[i]];
//        //循环遍历 找到父model
//        for (ManageStrutureModel *parentsModel in arr) {
//            if ([parentsModel.itemId isEqualToString:sonModel.parentItemId]) {
//                parentId=[parentsModel.parentItemId copy];
//                break;
//            }
//        }
//    }
//    return parentId;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    //如果超过2个 只显示2个分级
//    if (_dataDict.allKeys.count>=2) {
//        NSMutableArray *levelTypeArr=[_dataDict objectForKey:_dictKeys[_dictKeys.count-2+section]];
//        if (levelTypeArr.count>0) {
//            //取出一个model 获取他的parentid
//            ManageStrutureModel *model=[levelTypeArr firstObject];
//            NSString *parentId=[self getParentsIdWithModel:model];
//            
//            if (parentId) {
//                //NSMutableArray *parentsArr=[self.manageModel.dataDict objectForKey:parentId];
//                NSInteger count=0;
//                for (NSInteger i=0; i<_dataDict.allKeys.count; i++) {
//                    NSMutableArray *arr=_dataDict[_dataDict.allKeys[i]];
//                    //循环遍历 找到父model
//                    for (ManageStrutureModel *parentsModel in arr) {
//                        if ([[self getParentsIdWithModel:parentsModel] isEqualToString:parentId]) {
//                            parentId;
//                            break;
//                        }
//                    }
//                    
//                    //                    if (arr.count>0) {
//                    //                        ManageStrutureModel *newModel=[arr firstObject];
//                    //                        if ([[self getParentsIdWithModel:newModel] isEqualToString:parentId]) {
//                    //                            [_sonArr addObject:arr];
//                    //                            count++;
//                    //                        }
//                    //                    }
//                    
//                }
//                return count;
//            }
//        }
//        return levelTypeArr.count;
//    }else if (_dataDict.allKeys.count>0){
//        NSMutableArray *levelTypeArr=[_dataDict objectForKey:[_dictKeys firstObject]];
//        return levelTypeArr.count;
//    }
//    return 0;
//}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellID=@"PersonSelectTableViewCell";
    PersonSelectTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    //如果超过2个则 只显示2个分级
    NSMutableArray *levelTypeArr=nil;
    if (_dataDict.allKeys.count>=2) {
        levelTypeArr=[_dataDict objectForKey:_dictKeys[_dictKeys.count-2+indexPath.section]];
    }else if (_dataDict.allKeys.count>0){
        levelTypeArr=[_dataDict objectForKey:[_dataDict.allKeys firstObject]];
    }
    if (!cell) {
        cell=[[PersonSelectTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID indexPath:indexPath model:levelTypeArr[indexPath.row]];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        __weak PersonSelectViewController *mySelf=self;
        //增加部门或人员到列表中
        cell.addBlock=^(ManageStrutureModel *model){
            [mySelf addManageModelWithModel:model];
        };
        //从列表中删除部门或人员
        cell.deleteBlock=^(ManageStrutureModel *model){
            [mySelf deleteManageModelWithModel:model];
        };
        //增加人员到数组中
        cell.addPersonBlock=^(ManageStrutureModel *model){
            if (![mySelf.personArr containsObject:model]) {
                [mySelf.personArr addObject:model];
            }
        };
        //从数组中删除人员
        cell.deletePersonBlock=^(ManageStrutureModel *model){
            if ([mySelf.personArr containsObject:model]) {
                [mySelf.personArr removeObject:model];
            }
        };
    }
    [cell setCellWithManageModel:levelTypeArr[indexPath.row] indexPath:indexPath];
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //只有在3个分级时显示 返回上一级按钮
    if (section==0&&_dataDict.allKeys.count>2) {
        UIView *backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, 46)];
        backView.backgroundColor=[UIColor clearColor];
        
        _backButton=[MyControl creatButtonWithFrame:CGRectMake(IPHONE_WIDTH-90,8, 80, 30) target:self sel:@selector(backButtonClick) tag:220 image:nil title:@"返回上一级"];
        [_backButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _backButton.backgroundColor=[UIColor orangeColor];
        _backButton.layer.masksToBounds=YES;
        _backButton.layer.cornerRadius=5;
        //    _backButton.layer.borderColor=[[UIColor lightGrayColor]CGColor];
        //    _backButton.layer.borderWidth=1.0;
        _backButton.titleLabel.font=FONT_14;
        [backView addSubview:_backButton];
        //分割线
        UILabel *lineLabel=[[UILabel alloc]initWithFrame:CGRectMake(0, 45, IPHONE_WIDTH, 1)];
        lineLabel.backgroundColor=BACKCOLOR_GRAY;
        [backView addSubview:lineLabel];
        return backView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height=0;
    NSMutableArray *levelTypeArr;
    if (_dataDict.allKeys.count>=2) {
        levelTypeArr=[_dataDict objectForKey:_dictKeys[_dictKeys.count-2+indexPath.section]];
    }else if (_dataDict.allKeys.count>0){
        levelTypeArr=[_dataDict objectForKey:[_dataDict.allKeys firstObject]];
    }
    //如果余数不为0 则要多显示一行
    ManageStrutureModel *model=levelTypeArr[indexPath.row];
    if (model.dataArr.count%3==0) {
        height=model.dataArr.count/3*(30+15)+15+28;
    }else{
        height=(model.dataArr.count/3+1)*(30+15)+15+28;
    }
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0&&_dataDict.allKeys.count>2) {
        return 46;
    }
    return 0;
}
//
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
